package com.cloudcross.ssp.service.impl;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cloudcross.ssp.base.dao.GenericIBatisDao;
import com.cloudcross.ssp.base.web.SimpleController;
import com.cloudcross.ssp.common.Config;
import com.cloudcross.ssp.common.utils.DateUtil;
import com.cloudcross.ssp.common.utils.DateUtil.DateFmts;
import com.cloudcross.ssp.common.utils.MapBuilder;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.common.utils.SqlHelper;
import com.cloudcross.ssp.model.Account;
import com.cloudcross.ssp.model.BannerTemplate;
import com.cloudcross.ssp.model.Size;
import com.cloudcross.ssp.service.IBannerTemplateService;
import com.cloudcross.ssp.service.ISizeService;

@Service
public class BannerTemplateService extends SimpleController implements IBannerTemplateService {

    private Logger LOG = LogManager.getLogger(getClass());

    @Autowired
    private GenericIBatisDao myBatisDao;
    @Autowired
    private ISizeService sizeService;
    @Autowired
    Config config;

    @Override
    public BannerTemplate findById(Long id) {
        return myBatisDao.get("bannerTemplateSqlMapper.findById", id);
    }

    @Override
    public int countByParams(Map<String, Object> paramMap) {
        // 这里的搜索只是对名称进行搜索
        String searchValue = SqlHelper.doLike(paramMap.get("searchValue"));
        paramMap.put("key", paramMap.get("searchKey"));
        paramMap.put("value", searchValue);
        return myBatisDao.get("bannerTemplateSqlMapper.countByParams", paramMap);
    }

    @Override
    public List<BannerTemplate> findByParams(Map<String, Object> paramMap, Pager pager) {
        // 这里的搜索只是对名称进行搜索
        String searchValue = SqlHelper.doLike(paramMap.get("searchValue"));
        paramMap.put("key", paramMap.get("searchKey"));
        paramMap.put("value", searchValue);
        paramMap.put("pager", pager);
        return myBatisDao.getList("bannerTemplateSqlMapper.findByParams", paramMap);
    }

    @Override
    public boolean add(BannerTemplate t) {
        t.setUpdated(new Date());
        myBatisDao.save("bannerTemplateSqlMapper.addBannerTemplate", t);
        return true;
    }

    @Override
    public boolean save(BannerTemplate bannerTemplate, Map<String, Object> targetParamsMap) {
        return false;
    }

    // 素材替换上传更新
    @Override
    public boolean edit(BannerTemplate t) {
        Date date = new Date();
        t.setUpdated(date);
        myBatisDao.save("bannerTemplateSqlMapper.editadvertiser", t);
        // 更新素材对应创意审核状态
        Long id = t.getId();
        myBatisDao.save("bannerTemplateSqlMapper.updataBannerReplace",
                MapBuilder.create(HashMap.class).add("id", id).add("updated", date).add("supdated", date.getTime() / 1000).map());
        // 更新素材对应运营商审核状态
        myBatisDao.save("bannerTemplateSqlMapper.updataBannerOperatorReplace",
                MapBuilder.create(HashMap.class).add("id", id).add("supdated", date.getTime() / 1000).map());
        return true;
    }

    public boolean editOperator(BannerTemplate t) {
        t.setUpdated(new Date());
        myBatisDao.save("bannerTemplateSqlMapper.editoperator", t);
        return true;
    }

    @Override
    public boolean updataIds(BannerTemplate t) {
        t.setUpdated(new Date());
        myBatisDao.save("advertiser.bannerTemplateSqlMapper.updataIds", t);
        return true;
    }

    @Override
    public boolean updateStatus(List<Long> idList, int status) {
        Date date = new Date();
        myBatisDao.save("bannerTemplateSqlMapper.updateBannerTemplateStatus",
                MapBuilder.create(HashMap.class).add("status", status).add("idList", idList).add("updated", date).map());
        // 更形创意时间
        Long supdated = date.getTime() / 1000;
        myBatisDao.save("bannerTemplateSqlMapper.updateBannerTime",
                MapBuilder.create(HashMap.class).add("idList", idList).add("updataTime", supdated).map());
        // 更形素材运营商素材审核时间
        myBatisDao.save("bannerTemplateSqlMapper.updateBannerOperatorTime",
                MapBuilder.create(HashMap.class).add("idList", idList).add("updataTime", supdated).map());
        return true;

    }

    public boolean updateStatusOperator(List<Long> idList, int status) {
        myBatisDao.save("bannerTemplateSqlMapper.updateBannerTemplateStatus",
                MapBuilder.create(HashMap.class).add("status", status).add("idList", idList).add("updated", new Date()).map());
        return true;
    }

    @Override
    public boolean deleteUpdata(List<Long> idList, int status) {
        Date date = new Date();
        Long supdated = date.getTime() / 1000;
        // 删除创意素材
        myBatisDao.save("bannerTemplateSqlMapper.updataDeleteBannerTemplateStatus",
                MapBuilder.create(HashMap.class).add("status", status).add("idList", idList).add("updated", date).map());
        // 删除创意
        myBatisDao.save("bannerTemplateSqlMapper.updataDeleteBannerStatus",
                MapBuilder.create(HashMap.class).add("status", status).add("idList", idList).add("updated", date).add("supdated", supdated).map());
        // 更新运营商素材状态
        myBatisDao.save("bannerTemplateSqlMapper.updataDeleteBannerTemplateOperatorStatus",
                MapBuilder.create(HashMap.class).add("status", status).add("idList", idList).add("supdated", supdated).map());
        return true;
    }

    @Override
    public boolean alterName(Map<String, Object> paramMap) {
        myBatisDao.save("bannerTemplateSqlMapper.alterName", paramMap);
        return true;
    }

    @Override
    public int countByParams2(Map<String, Object> paramMap) {
        // 这里的搜索只是对名称进行搜索
        String searchValue = SqlHelper.doLike(paramMap.get("searchValue"));
        paramMap.put("key", paramMap.get("searchKey"));
        paramMap.put("value", searchValue);
        if (!paramMap.containsKey("width") || (paramMap.get("width")).equals("")) {
            paramMap.put("width", null);
        }
        if (!paramMap.containsKey("height") || (paramMap.get("height")).equals("")) {
            paramMap.put("height", null);
        }
        if (!paramMap.containsKey("type") || (paramMap.get("type")).equals("")) {
            paramMap.put("type", null);
        }
        if (!paramMap.containsKey("status") || (paramMap.get("status")).equals("")) {
            paramMap.put("status", null);
        }
        if (!paramMap.containsKey("advertiserId") || (paramMap.get("advertiserId")).equals("") || (paramMap.get("advertiserId")).equals("-1")) {
            paramMap.put("advertiserId", null);
        }
        return myBatisDao.get("bannerTemplateSqlMapper.countByParams2advertiser", paramMap);
    }

    public int countByParams2Operator(Map<String, Object> paramMap) {
        // 这里的搜索只是对名称进行搜索
        String searchValue = SqlHelper.doLike(paramMap.get("searchValue"));
        paramMap.put("key", paramMap.get("searchKey"));
        paramMap.put("value", searchValue);
        return myBatisDao.get("bannerTemplateSqlMapper.countByParams2operator", paramMap);
    }

    @Override
    public List<BannerTemplate> findByParams2(Map<String, Object> paramMap, Pager pager) {
        // 这里的搜索只是对名称进行搜索
        String searchValue = SqlHelper.doLike(paramMap.get("searchValue"));
        paramMap.put("key", paramMap.get("searchKey"));
        paramMap.put("value", searchValue);
        paramMap.put("pager", pager);
        return myBatisDao.getList("bannerTemplateSqlMapper.findByParams2advertiser", paramMap);
    }

    @Override
    public List<BannerTemplate> findByParams2Ext(Map<String, Object> paramMap) {
        // 这里的搜索只是对名称进行搜索
        String searchValue = SqlHelper.doLike(paramMap.get("searchValue"));
        paramMap.put("key", paramMap.get("searchKey"));
        paramMap.put("value", searchValue);
        return myBatisDao.getList("bannerTemplateSqlMapper.findByParams2advertiserExt", paramMap);
    }

    public List<BannerTemplate> findByParams2Operator(Map<String, Object> paramMap, Pager pager) {
        // 这里的搜索只是对名称进行搜索
        String searchValue = SqlHelper.doLike(paramMap.get("searchValue"));
        paramMap.put("key", paramMap.get("searchKey"));
        paramMap.put("value", searchValue);
        paramMap.put("pager", pager);
        return myBatisDao.getList("bannerTemplateSqlMapper.findByParams2Operator", paramMap);
    }

    @Override
    public int countByParams3(Map<String, Object> paramMap) {
        String searchValue = SqlHelper.doLike(paramMap.get("searchValue"));
        paramMap.put("key", paramMap.get("searchKey"));
        paramMap.put("value", searchValue);
        if (paramMap.get("height") == "" || paramMap.get("width") == "") {
            paramMap.put("width", null);
            paramMap.put("height", null);
        }
        if (paramMap.get("type") == "") {
            paramMap.put("type", null);
        }
        return myBatisDao.get("bannerTemplateSqlMapper.countByParams3advertiser", paramMap);
    }

    public int countByParams3Operator(Map<String, Object> paramMap) {
        return myBatisDao.get("bannerTemplateSqlMapper.countByParams3operator", paramMap);
    }

    @Override
    public List<BannerTemplate> findByParams4(Map<String, Object> paramMap, Pager pager) {
        paramMap.put("pager", pager);
        String searchValue = SqlHelper.doLike(paramMap.get("searchValue"));
        paramMap.put("key", paramMap.get("searchKey"));
        paramMap.put("value", searchValue);
        paramMap.put("pager", pager);
        if (paramMap.get("height") == "" || paramMap.get("width") == "") {
            paramMap.put("width", null);
            paramMap.put("height", null);
        }
        if (paramMap.get("type") == "") {
            paramMap.put("type", null);
        }
        return myBatisDao.getList("bannerTemplateSqlMapper.findByParams4advertiser", paramMap);
    }

    public List<BannerTemplate> findByParams4Operator(Map<String, Object> paramMap, Pager pager) {
        paramMap.put("pager", pager);
        return myBatisDao.getList("bannerTemplateSqlMapper.findByParams4operator", paramMap);
    }

    @Override
    public String resetName(String uploadName) {
        String fileType = uploadName.substring(uploadName.lastIndexOf("."));
        uploadName = new StringBuilder().append(System.currentTimeMillis()).append(fileType).toString();
        return uploadName;
    }

    @Override
    public String getLocalFilePath(String fileName) {
        Account loginUser = getLoginUser();
        // 计算相对路径名，即不包括默认路径名
        String path = new StringBuilder().append(File.separator).append(loginUser == null ? "anon" : loginUser.getId()).append(File.separator)
                .append(DateUtil.getDate(DateFmts.YYYYMMDD)).append(File.separator).append(System.currentTimeMillis()).append(File.separator)
                .append(fileName).toString();
        String localFilePath = config.getResourceUploadDir().concat(File.separator).concat("banner").concat(path);
        // 计算在容器中实际路径名,添加文件所运行所在的实际目录
        String accessUrl = localFilePath;
        ServletContext servletContext = getServletContext();
        if (servletContext == null) {
            LOG.debug("单体测试情况，servletContext不存在。");
        } else {
            accessUrl = servletContext.getRealPath("/");
            File upFile = new File(accessUrl);
            accessUrl = upFile.getParent();
            // 获取绝对路径
            localFilePath = accessUrl.concat(File.separator).concat(localFilePath);
        }
        return localFilePath;
    }

    @Override
    public String replacePath(String path) {
        path = path.substring(path.indexOf("upload") - 1);
        return path;
    }

    @Override
    public int judgeType(String fileType) {
        int type = 2;
        if ("jpg".equalsIgnoreCase(fileType) || "jpeg".equalsIgnoreCase(fileType) || "gif".equalsIgnoreCase(fileType)
                || "png".equalsIgnoreCase(fileType)) {
            type = 2;
        } else if ("flv".equalsIgnoreCase(fileType) || "mp4".equalsIgnoreCase(fileType)) {
            type = 3;
        } else {
            type = 1;
        }
        return type;
    }

    @Override
    public void compressPicture(File localFile, String pathNew, int width, int height) throws IOException {
        // 新建缩略图文件
        File newFile = new File(pathNew);
        if (!newFile.getParentFile().exists()) {
            newFile.getParentFile().mkdirs();
        }
        // 构造image图片
        Image src = javax.imageio.ImageIO.read(localFile);
        // 表示该图像具有打包成整数的像素的8 位RGB颜色分量
        BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        // h绘制缩小后的图片
        tag.getGraphics().drawImage(src, 0, 0, width, height, null);
        // 生成缩略图
        ImageIO.write(tag, "png", newFile);
    }

    @Override
    public BannerTemplate suitSize(int width, int height, BannerTemplate bannerTemplate) {
        // 构造image图片
        Size size = new Size();
        // 查找所有广告位
        List<Size> sizeList = sizeService.findAllSize();
        long _width[] = new long[sizeList.size()];
        long _height[] = new long[sizeList.size()];
        for (int i = 0; i < sizeList.size(); i++) {
            size = sizeList.get(i);
            _width[i] = size.getWidth();
            _height[i] = size.getHeight();
            if (width == _width[i] && height == _height[i]) {
                bannerTemplate.setWidth((long) width);
                bannerTemplate.setHeight((long) height);
                bannerTemplate.setRwidth(size.getRwidth());
                bannerTemplate.setRheight(size.getRheight());
                return bannerTemplate;
            }
        }
        bannerTemplate = null;
        return bannerTemplate;
    }
}
